
/* 获取本地对象信息 */
export const getLacalInfo = (key: string) => {
  var info = window.localStorage.getItem(key);
  if (typeof info === "string") {
    return info;
  } else if (typeof info === "object" && info !== null) {
    return JSON.parse(info);
  }
};

/* 设置本地对象信息 */
export const setLocalInfo = (key: string, value: any) => {
  window.localStorage.setItem(key, value);
};

/* 检查是不是移动端 */
export const isMobile = () => {
  //获取浏览器navigator对象的userAgent属性（浏览器用于HTTP请求的用户代理头的值）
  var info = navigator.userAgent;
  //通过正则表达式的test方法判断是否包含“Mobile”字符串
  var isPhone = /mobile/i.test(info);
  //如果包含“Mobile”（是手机设备）则返回true
  return isPhone;
};
/* 检查是不是PC */
export function isPc() {
  return /(Win32|Win16|WinCE|Mac68K|MacIntel|MacIntel|MacPPC|Linux mips64)/i.test(
    navigator.platform
  );
}

/* 生成随机数字 */
export const randomNumber = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min + 1) + min);
};

/* 生成随机颜色 */
export const randomColor = () => {
  return `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
};

export const uuid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}


export const copyText = (text: string) => {
  // 添加一个input元素放置需要的文本内容
  const copyContent = document.createElement('input');
  copyContent.value = text;
  document.body.appendChild(copyContent);
  // 选中并复制文本到剪切板
  copyContent.select();
  document.execCommand('copy');
  // 移除input元素
  document.body.removeChild(copyContent);
};


/**
 * element           要绑定事件的对象及HTML节点。
 * type              事件名称attachEvent监听的事件前边的加上“on”比如“onclick”和“onmouseover”addEventListener与之相反。
 * listener          要绑定的事件监听函数
 */
/* eslint-disable */
type eventType = "mousedown" | "mousemove" | "contextmenu" | string
export const addEvent = function (element: any, type: eventType, callback: any) {
  if (element.addEventListener) {
    // 支持使用 addEventListener()
    if (type.slice(0, 2) === "on")
      // 以 "on" 开头不需要则去掉
      type = type.slice(2);
    element.addEventListener(type, callback);
  } else if (element.attachEvent) {
    // 支持使用 attachEvent()
    if (type.slice(0, 2) !== "on")
      // 没有以 "on" 开头需要则加上
      type = "on" + type;
    element.attachEvent(type, callback);
  } else {
    type.slice(0, 2) !== "on"
      ? (element["on" + type] = callback)
      : (element[type] = callback);
  }
};
/**
 * @description 复制
 * @param {*} id DOM ID
 */
export const copyDomText = (node: HTMLElement) => {
  let createRange = document.createRange();
  createRange.selectNodeContents(node);
  const selection = document.getSelection() as Selection;
  selection.removeAllRanges();
  selection.addRange(createRange);
  document.execCommand("Copy");
  selection.removeAllRanges();
};

export const createStyle = (code: string) => {
  var style = document.createElement("style");
  //for Chrome Firefox Opera Safari
  style.appendChild(document.createTextNode(code));
  //for IE
  //style.styleSheet.cssText = code;
  var head = document.getElementsByTagName("head")[0];
  head.appendChild(style);
};
export const openLink = (href: string) => {
  var link = document.createElement("a") as HTMLAnchorElement;
  link.href = href;
  link.target = "_blank";
  document.body.append(link);
  link.click();
  setTimeout(() => link.parentNode?.removeChild(link));
};

// 删除事件
export function removeEvent(el: any, event: String, handler: Function) {
  if (!el) {
    return
  }
  if (el.detachEvent) {
    el.detachEvent('on' + event, handler)
  } else if (el.removeEventListener) {
    el.removeEventListener(event, handler, true)
  } else {
    el['on' + event] = null
  }
}

export const downloadText = (text: string, filename: string = "") => {
  if (filename === "" || !filename) {
    filename = uuid().slice(0, 5)
  }

  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

/* 格式化文件 */
export const formatCode = (code: any, tabIndex = 2, func?: () => any): string => {
  return JSON.stringify(code, func, tabIndex)
}

/**
 * todo:精确检测类型,返回小写值
 *  */
export const getObjectType = (obj: any) => {
  var type = Object.prototype.toString.call(obj)
  return type.slice(7, -1).toLowerCase().trim()
}

/**
 * todo:检测属性是否包含子属性
 *  */
export const hasProperties = (prop: any) => {
  return Object.keys(prop).length >= 0
}

/**
 * todo:方法描述
 *  */
export const loadImage = (imageName: string) => {
  return new URL(`../assets/${imageName}`, import.meta.url).href;
}


/**
 * todo:blob转文件并下载
 *  */
export const downloadBlob = (blob: Blob, fileName = "file") => {
  let blobUrl = window.URL.createObjectURL(blob)
  let link = document.createElement('a')
  link.download = fileName || 'defaultName'
  link.style.display = 'none'
  link.href = blobUrl
  // 触发点击
  document.body.appendChild(link)
  link.click()
  // 移除
  document.body.removeChild(link)
}
// 调用

/**
 * todo:方法描述
 *  */
export const downloadImage = (base64: string, name: string) => {
  let img = new Image()
  img.setAttribute('crossOrigin', 'Anonymous')
  img.onload = function () {
    let canvas = document.createElement('canvas')
    let context = canvas.getContext('2d')
    canvas.width = img.width
    canvas.height = img.height
    if (!context) return
    context.drawImage(img, 0, 0, img.width, img.height)
    let url = canvas.toDataURL('images/png')
    let a = document.createElement('a')
    let event = new MouseEvent('click')
    a.download = name || 'default.png'
    a.href = url
    a.dispatchEvent(event)
  }
  img.src = base64

}